package app.util.image
{
	import app.util.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filesystem.*;
	import flash.net.*;
	import flash.utils.*;
	
	import mx.graphics.codec.*;
	
	public class ImageIO
	{
		public function openImage(f:File):void
		{
			//Try to parse the image
			var fileName:String = f.url;
			var loader:URLLoader = new URLLoader();
	      	loader.dataFormat = URLLoaderDataFormat.BINARY;
	    	loader.addEventListener(Event.COMPLETE, function(e:Event):void
	    	{
	    		var bytes:ByteArray = loader.data;
		        try
		        {
		        	openImageData(new BMPDecoder().decode(bytes), f);
			    }
			    catch(er:VerifyError)
			    {	
	                var contentLoader:Loader = new Loader(); 
	                contentLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, 
	                	function(e:Event):void 
	                	{         		
	                		openImageData(Bitmap(e.target.content).bitmapData, f);
	                	}); 
	                contentLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, 
	                	function(e:IOErrorEvent):void 
	                	{
	                		Mediator.alert("Unknown file type : " + f.name);
	                	});
					try
					{                	
	                	contentLoader.loadBytes(bytes);
	    			}
	      			catch(er:Error)
	      			{
	      				trace("Content loader error : " + er.message);
	      				Mediator.getLogger().log("Content loader parser failure for unknown format");
	      			}
	        	}
	    	});
	     	loader.load(new URLRequest(fileName));	
		}
		
		public function saveImage(f:File, type:int, checkExt:Boolean, data:BitmapData):void
		{		
			var bytes:ByteArray = null;
			var ext:String;
			switch(type)
			{
				case ImageConfig.JPEG_TYPE:
					bytes = new JPEGEncoder().encode(data);
					ext = "jpg";
					break;
				case ImageConfig.PNG_TYPE:
					bytes = new PNGEncoder().encode(data);
					ext = "png";
					break;
				case ImageConfig.BMP_TYPE:
					bytes = new BMPEncoder().encode(data);
					ext = "bmp";
					break;						
			}
			
			if(bytes == null)
			{
				throw new Error("Invalid image file type");	
			}
			
			if(checkExt && (!f.extension || f.extension.toLowerCase() != ext))
			{
				f.nativePath += ("." + ext);
			}
			
			var stream:FileStream = new FileStream(); 
            stream.open(f, FileMode.WRITE); 
            stream.writeBytes(bytes);
            stream.close(); 
            
            Mediator.alert("Save to " + f.name + " done");
		}		
    	
    	private function openImageData(d:BitmapData, f:File):void
    	{
    		//Check transparency
    		if(!d.transparent)
    		{
    			try
    			{
    				var tmp:BitmapData = new BitmapData(d.width, d.height, true, 0x0);
    				tmp.draw(d);
    				d = tmp;
    				Mediator.alert("Open image file " + f.name + " done");	
    			}
    			catch(e:Error)
    			{
    				if(Mediator.getConfig().allowRestrict)
    				{
    					Mediator.alert("Image is too large. The application will be running at restrict mode");
    				}
    				else
    				{
    					Mediator.alert("Image is too large. The application will not open it. If you want to run it in force, enable 'Restrict Mode' in settings");
    					return;
    				}
    			}
    		}
    		else
    		{
    			Mediator.alert("Open image file " + f.name + " done");	
    		}
    		
    		//Open in appliaction
    		var cfg:ImageConfig = new ImageConfig(d);
    		var type:int;
    		switch(f.extension.toLowerCase())
    		{
    			case 'jpg':
    			case 'jpeg':
    				type = ImageConfig.JPEG_TYPE;
    				break;
    			case 'png':
    				type = ImageConfig.PNG_TYPE;
    				break;
    			case 'bmp':
    				type = ImageConfig.BMP_TYPE;
    				break;    	
    			default:
    				Mediator.getLogger().log("Invalid image file type for unknown ext : " + f.extension);
    				throw new Error("Invalid image file type");			
    		}
    		
    		cfg.file = f;
    		cfg.fileType = type;
   			
    		Mediator.getMain().displayer.createImage(cfg);
    	}
	}
}